﻿using FSM.IDal;
using FSM.Model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using Util.DataBase;

namespace FSM.Dal
{
    public class TablesDal : BaseDbContext, ITablesDal
    {
        /// <summary>
        /// 获得所有的数据库信息
        /// </summary>
        /// <returns></returns>
        public List<Schemas> GetDataBases()
        {
            string strSQL = @"SELECT
	                                * 
                                FROM
	                                information_schema.SCHEMATA 
                                WHERE
	                                schema_name <> 'information_schema'";
            List<Schemas> result = dbContext.SqlQueryable<Schemas>(strSQL).ToList();
            return result;
        }

        /// <summary>
        /// 获得数据库中的所有表的信息
        /// </summary>
        /// <returns></returns>
        public List<SchemaTables> GetTables(string database_name)
        {
            string strSQL = @"SELECT
                                    *
                                FROM                                
                                    information_schema.`TABLES` 
                                WHERE
                                    table_schema = @table_schema";
            List<SugarParameter> parameters = new List<SugarParameter>();
            parameters.Add(new SugarParameter("table_schema", database_name));
            List<SchemaTables> result = dbContext.Ado.SqlQuery<SchemaTables>(strSQL, parameters);
            return result;
        }

        /// <summary>
        /// 获得数据表的字段信息
        /// </summary>
        /// <param name="database_name">数据库名称</param>
        /// <param name="table_name">表名称</param>
        /// <returns></returns>
        public List<TableFields> GetFields(string database_name, string table_name)
        {
            string strSQL = @"SELECT
	                                * 
                                FROM
	                                information_schema.`COLUMNS` 
                                WHERE
	                                TABLE_SCHEMA = @table_schema 
	                                AND TABLE_NAME = @table_name";
            List<SugarParameter> parameters = new List<SugarParameter>();
            parameters.Add(new SugarParameter("table_schema", database_name));
            parameters.Add(new SugarParameter("table_name", table_name));
            List<TableFields> result = dbContext.Ado.SqlQuery<TableFields>(strSQL, parameters);
            return result;
        }
    }
}
